<?php
/**
 * @Author: hpp
 * @Date:   2018-12-04 17:57:46
 * @Last Modified by:   hpp
 * @Last Modified time: 2018-12-07 14:37:30
 */
namespace app\admin\controller;

use think\Request;
use \tp5er\Backup;
use think\Db;
class Data extends BaseController
{
	protected $backup = null;
	protected $config;
	public function initialize()
	{
		parent::initialize();
		$this->config = config('backup.');
		$this->backup = new Backup($this->config);
	}

	/**
	 * 数据库列表
	 */
	public function index()
	{
		$list = $this->backup->dataList();
		foreach ($list as $k => $v) {
			$list[$k]['total_length'] = $v['data_length'] + $v['index_length'];
		}
		return $this->fetch('index',compact('list'));
	}

	/**
	 * 备份表
	 */
	public function backup(Request $request){
		$tables = $request->tables;
		$index = $request->index;
		$start = $request->start;
		if ($request->isPost() && !empty($tables) && is_array($tables)) {
			// 初始化创建备份文件
			if (!is_dir($this->config['path'])) {
				mkdir($this->config['path'],0755,true);
			}
			$lock = $this->config['path'].'backup.lock';
			if (is_file($lock)) {
				return json(['code' => 0,'msg' => '备份正在进行...']);
			}else{
				// 创建锁文件
				file_put_contents($lock,time());
			}
			$file = ['name' => date('Ymd-His',time()),'part' => 1]; // 备份文件名字
			session('backup_tables', $tables);
			session('backup_file',$file);
			$backup = new Backup($this->config,$file);
			if (false == $backup->Backup_Init()) {
				return json(['code' => 0,'msg' => '初始化失败']);
			}
			return json(['code' => 1,'msg' => '初始化成功','data' => ['index' => 0,'start' => 0],'tables' => $tables]);
			
		}elseif($request->isGet() && is_numeric($index) && is_numeric($start)){
			$tables = session('backup_tables');
			$file = session('backup_file');
			$backup = new Backup($this->config,$file);
			$start  = $backup->backup($tables[$index], $start);
			if (false == $start && $start != 0) {
				return json(['code' => 0,'msg' => '备份出错']);
			}elseif (0 == $start) {
				// 备份下一个表
				if(isset($tables[++$index])){
					
                    $tab = array('index' => $index, 'start' => 0);
                    return json(['code' => 3,'msg' => '开始备份下一个','data' => $tab,'rate' => 100]);
                } else { //备份完成，清空缓存
                    unlink($this->config['path'].'backup.lock');
                    session('backup_tables', null);
                    session('backup_file',null);
                    return json(['code' => 1,'msg' => '备份完成','rate' => 100]);
                }
			}else{
				// 正在备份
				$tab  = array('index' => $index, 'start' => $start[0]);
                $rate = floor(100 * ($start[0] / $start[1]));
                return json(['code' => 2,'msg' => "正在备份...({$rate}%)",'data' => $tab,'rate' => $rate]);
			}
		}else{
			return json(['code' => 0,'msg' => '参数错误']);
		}
	}

	/**
	 * 优化表/修复
	 */
	public function optimizeAndRepair()
	{
		$table = input('get.tableName');
		if (!$table) {
			return json('请指定要优化的表！');
		}
		$type = input('get.type');
		try {
			$table = explode(',', $table);
			switch ($type) {
				case 'optimize':
					$res = $this->backup->optimize($table);
					$error = '优化';
					break;
				case 'repair':
					$res = $this->backup->repair($table);
					$error = '修复';
					break;	
				default:
					$res = false;
					$error = '未知错误';
					break;
			}
			if ($res) {
				return json(['code' => 1,'msg' => $error.'成功']);
			}else{
				return json(['code' => 0,'msg' => '数据表'.$error.'出错请重试']);
			}
		} catch (\Exception $e) {
			$msg = $e->getMessage();
			return json(['code' => 0,'msg' => $msg]);
		}
	}
}